#include "mainwindow.h"
#include <QTableWidget>
#include <QVBoxLayout>
#include <QLabel>

MainWindow::MainWindow(QWidget *parent) : QWidget(parent)
{
    tableWidget = new QTableWidget(8, 6, this);
    statue = new QLabel(this);
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(tableWidget);
    mainLayout->addWidget(statue);
    setLayout(mainLayout);

    // 获取slectionModel
    QItemSelectionModel *selectionModel = tableWidget->selectionModel();

    //设置选区，并选中
    QModelIndex topLeft = tableWidget->model()->index(0, 0, QModelIndex());
    QModelIndex bottomRight = tableWidget->model()->index(7, 5, QModelIndex());
    QItemSelection selection(topLeft, bottomRight);
    // QItemSelectionModel::Select表示选中选区内的元素
    // QItemSelectionModel::Deselect 表示取消选区中已经选中的元素
    // QItemSelectionModel::Toggle 表示选区内元素反选(未选择->选中；选中->未选择)
    selectionModel->select(QItemSelection(topLeft, topLeft), QItemSelectionModel::Select);
    selectionModel->select(selection, QItemSelectionModel::Toggle);

    //连接选区发生改变的信号到updateSelection函数
    connect(selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
            this, SLOT(updateSelection(QItemSelection,QItemSelection)));
    // 连接currentXChanged信号到changeCurrent函数
    connect(selectionModel, SIGNAL(currentChanged(QModelIndex,QModelIndex)),
            this, SLOT(changCurrent(QModelIndex,QModelIndex)));
}

MainWindow::~MainWindow()
{

}

void MainWindow::updateSelection(const QItemSelection &selected, const QItemSelection &deselected)
{
    // 获取选区所有元素的index
    QModelIndexList indexs = selected.indexes();
    QModelIndex index;

    // 设置选区的元素的model
    foreach (index, indexs) {
        QString text = QString("(%1, %2)").arg(index.column()).arg(index.row());
        tableWidget->model()->setData(index, text);
    }
    // 以前选区的数据修改未空字符串
    indexs = deselected.indexes();
    foreach (index, indexs) {
        tableWidget->model()->setData(index, "");
    }
}
/*
 * current 保存改变后的index, previous为改变前的index
 */
void MainWindow::changCurrent(const QModelIndex &current, const QModelIndex &previous)
{
    statue->setText(QString("Move (%1, %2) to (%3, %4)")
                    .arg(current.column()).arg(current.row())
                    .arg(previous.column()).arg(previous.row()));
}

